package logic

import (
	"context"
	"edu/models/cache"
	"edu/pkg"
	"fmt"
	"math/rand"
	"strconv"
	"time"

	"edu/edurpc/edurpc"
	"edu/edurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *edurpc.SendSmsRequest) (*edurpc.SendSmsResponse, error) {
	timeCount, _ := cache.Rdb.Get(l.ctx, "smsCodeTime_"+in.Account).Int()
	if timeCount >= 1 {
		return nil, fmt.Errorf("一分钟内只允许发送一条")
	}
	code := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(in.Account, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if sms.Code != 2 {
		return nil, fmt.Errorf(sms.Msg)
	}
	cache.Rdb.Set(l.ctx, "smsCode_"+in.Account, code, time.Minute*5)

	cache.Rdb.Incr(l.ctx, "smsCodeTime_"+in.Account)
	cache.Rdb.Expire(l.ctx, "smsCodeTime_"+in.Account, time.Minute*1)
	return &edurpc.SendSmsResponse{}, nil
}
